package com.words.controller;

import com.words.entity.Cet6Words;
import com.words.service.WordService;
import com.words.result.Result;
import com.words.untils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/word")
public class WordController {

    @Autowired
    WordService wordService;

    @Autowired
    JwtTokenUtils jwtTokenUtils;

    //返回所有单词
    @GetMapping("/listAll")
    @PreAuthorize("hasAuthority('USER_FINDALL')")
    public Object ListAll() {
        List<Cet6Words> data = wordService.findAll();
        if(data.isEmpty()){
            return Result.init(201, "查询失败", data);
        }else {
            return Result.init(200, "查询成功", data);
        }

    }

    //获得指定单词
    @GetMapping("/query/{word}")
    @PreAuthorize("hasAuthority('USER_FINDONE')")
    public Object query(@PathVariable("word") String word) {
        List<Cet6Words> data = wordService.queryByWord(word);
        if(data.isEmpty()){
            return Result.init(201, "查询失败", data);
        }else {
            return Result.init(200, "查询成功", data);
        }
    }

    //给指定单词添加笔记
    @PostMapping("/addnote/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Object addNote(@PathVariable("id") int id, @RequestBody String note) {
        try{
            wordService.addNote(id, note);
        }catch (Exception e) {
            System.out.println(e);
            return Result.init(201, "添加失败", note);
        }
        return Result.init(200, "添加成功", null);
    }

    //给指定单词删除笔记
    @GetMapping("/deletenote/{id}")
    public Object deltedNote(@PathVariable("id") int id) {
        try{
            wordService.deleteNote(id);
        }catch (Exception e) {
            return Result.init(201, "删除失败", null);
        }
        return Result.init(200, "删除成功", null);
    }
    //测试
    @GetMapping("/test")
    public String test(HttpServletRequest request){
        String token= request.getHeader("token");
        String name= jwtTokenUtils.getVByToken(token,"username");
        return name+"成功进入到测试界面";
    }
}

